<%@page import="java.sql.PreparedStatement"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@ page import = "java.io.FileInputStream" %>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Student Edit Name</title>
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	<script src="js/jquery.ajaxfileupload-full.js"></script>
<script type="text/javascript">
	function change_readonly(tag_id) {
		document.getElementById(tag_id).readOnly = false;
		$('#edit_'+tag_id).remove();
		$('#'+tag_id).focus();
	}
	$(document).ready(function() {
			
		var src_path_full="null";
		$('input[type="file"]').ajaxfileupload({
			'action' : 'UploadServletAjaxFileAll',
			'onComplete' : function(response) {
				$('#upload').hide();
				$('#message').show();
				
				var statusVal = JSON.stringify(response.status);
					alert("statusVal:"+statusVal);
	
				if(statusVal == "false")
				{
					$("#message").html("<font color='red'>"+ JSON.stringify(response.message) +" </font>");
					
				}	
				if(statusVal == "true")
				{
					
					 var xmlhttp;
						
						if(window.XMLHttpRequest) {
							// code for IE7+, Firefox, Chrome, Opera, Safari
							xmlhttp = new XMLHttpRequest();
						}
						else {
							// code for IE6, IE5
							xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
						}
						
						xmlhttp.onreadystatechange = function() {
							if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {	
								
								alert("Back from student_edit_personal_get_photo_temp:");
								
					
															
							
									
								src_path_full = xmlhttp.responseText;
								
								alert("src_path_full:"+src_path_full);
								
								$("#file_upload").val(src_path_full); 
											
								 var file_name_old = $('#file').val();
							        
								 alert("file_name_old:"+file_name_old);
								$('#file_name_old').val(file_name_old);

							$("#message").html("<font color='green'>"+ JSON.stringify(response.message) +" </font>");		
									
							// end if check state
							}// end function
						
						}						
						xmlhttp.open("POST", "student_edit_personal_get_photo_temp.jsp", true);
						xmlhttp.send();
		
				}			
			},
			'onStart' : function() {
				$('#upload').show();
				$('#message').hide();
			}
		});
		
		
		
		
	});

	
</script>
</head>
<body>

<%	
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
			
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
		//////////get permission ///////////
			
		String name = String.valueOf(session.getAttribute("name"));
		String surname = String.valueOf(session.getAttribute("surname"));
		String role_name = String.valueOf(session.getAttribute("student_role"));
		
		String department_id2 = String.valueOf(session.getAttribute("department_id"));
		
		System.out.println("name : " + name);///////////////////////////////
		System.out.println("department_id : " + department_id2);/////////////////////////
		
		
		List<String> system_name = new ArrayList<String>();
		
		Permission permission = new Permission(strUser,name);
		permission.setDepartmentId(department_id2);
		permission.setStudentCreate(Boolean.valueOf(String.valueOf(session.getAttribute("student_create"))));
		permission.setStudentDelete(Boolean.valueOf(String.valueOf(session.getAttribute("student_delete"))));
		permission.setStudentRead(Boolean.valueOf(String.valueOf(session.getAttribute("student_read"))));
		permission.setStudentUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("student_update"))));
		
		String permiss = "";
		if(permission.getStudentCreate()) {
			permiss = permiss + "Add";
		}
		if(permission.getStudentUpdate()) {
			if("".equals(permiss)) {
				permiss = permiss + "Edit";
			} else {
				permiss = permiss + " Edit";
			}
		}
		if(permission.getStudentRead()) {
			if("".equals(permiss)) {
				permiss = permiss + "Read";
			} else {
				permiss = permiss + " Read";
			}
		}
		if(permission.getStudentDelete()) {
			if("".equals(permiss)) {
				permiss = permiss + "Delete";
			} else {
				permiss = permiss + " Delete";
			}
		}
		//check permission
		if(!permission.getStudentUpdate()){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_home.jsp"> 	
		<%}
	
	// get paremeter
	String studentId = request.getParameter("student_id");
	String tempId = studentId;
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	String checker = request.getParameter("checker");
	System.out.println("checker:   "+checker);
	// find name & surname from DB
	People people = new People();
	String student_id = "";
	
	try{
		ResultSet rs = connect.createStatement().executeQuery("SELECT S.student_id ,N.name_th, N.name_en, N.surname_th, N.surname_en, N.index, N.title_th, N.title_en " 
				+ " FROM student S, full_name N, people P " 
				+ " WHERE P.full_name_id=N.full_name_id AND S.index=P.index"
				+ " AND student_id='"+studentId+"'");
		
		if(rs.next()) {
			people.setNameTH(rs.getString("name_th"));
			people.setNameEN(rs.getString("name_en"));
			people.setSurnameTH(rs.getString("surname_th"));
			people.setSurnameEN(rs.getString("surname_en"));
			people.setIndex(rs.getString("index"));
			people.setTitleTH(rs.getString("title_th"));
			people.setTitleEN(rs.getString("title_en"));
			student_id = rs.getString("student_id");
		}
		
	}catch(Exception a){
		out.println(a.getMessage());
		a.printStackTrace();
		
	}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//if add new info do this !	
	if(request.getParameter("checker").equals("ADD")){		
				
					// get value from tag
					String index_new = request.getParameter("index");
					String title_th_new = new String(request.getParameter("title_th").getBytes("ISO8859_1"),"UTF-8");
					String title_en_new = request.getParameter("title_en");
					
					String name_th_old = new String(request.getParameter("name_th_old").getBytes("ISO8859_1"),"UTF-8");
					String surname_th_old = new String(request.getParameter("surname_th_old").getBytes("ISO8859_1"),"UTF-8");
					String name_en_old = request.getParameter("name_en_old");
					String surname_en_old = request.getParameter("surname_en_old");
					
					String name_th_new = new String(request.getParameter("name_th_new").getBytes("ISO8859_1"),"UTF-8");
					String surname_th_new = new String(request.getParameter("surname_th_new").getBytes("ISO8859_1"),"UTF-8");
					String name_en_new = request.getParameter("name_en_new");
					String surname_en_new = request.getParameter("surname_en_new");
					
					System.out.println("name_th_new +++++++++ : "+name_th_new);////////////////////try///////////////////
					System.out.println("surname_th_new: "+surname_th_new);////////////////////try///////////////////
					System.out.println("name_en_new : "+name_en_new);////////////////////try///////////////////
					System.out.println("surname_en_new : "+surname_en_new);////////////////////try///////////////////
					
					Pattern regex = Pattern.compile("[$&+,:;=?@#^*|!%<>]");
					Matcher matchername_th_new = regex.matcher(name_th_new);
					Matcher matchersurname_th_new = regex.matcher(surname_th_new);
					Matcher matchername_en_new = regex.matcher(name_en_new);
					Matcher matchersurname_en_new = regex.matcher(surname_en_new);
					Matcher matchertitle_th_new = regex.matcher(title_th_new);
					Matcher matchertitle_en_new = regex.matcher(title_en_new);
					
					if (matchername_th_new.find() || matchersurname_th_new.find() || matchername_en_new.find() || matchersurname_en_new.find() || matchertitle_th_new.find() || matchertitle_en_new.find()){
						%>
										<script language="javascript"> alert("ข้อมูลไม่ถูกต้อง โปรดใช้ตัวเลขหรือตัวอักษรเท่านั้น");	</script>
						<%}else{
							
						
					// get date
					java.util.Date dt = new java.util.Date();
					java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd",java.util.Locale.US);
					String date_now = sdf.format(dt);
					
					if(!name_th_old.equals(name_th_new) || !surname_th_old.equals(surname_th_new) || !name_en_old.equals(name_en_new) || !surname_en_old.equals(surname_en_new)) {
						try {			
							
							String sql = "INSERT INTO `full_name`(`index`, `title_th`, `title_en`, `name_th`, `name_en`, `surname_th`, `surname_en`, `date`) "
									+ " VALUES ('"+index_new+"', '"+title_th_new+"', '"+title_en_new+"', "
									+ " '"+name_th_new+"', '"+name_en_new+"', '"+surname_th_new+"', '"+surname_en_new+"', '"+date_now+"' ) ";
							PreparedStatement pstmt = connect.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
							
							pstmt.executeUpdate();  
							ResultSet keys = pstmt.getGeneratedKeys();    
							keys.next();  
							int key = keys.getInt(1);
							
							/* Log file */						
							String log_name = strUser+" "+name+" "+surname+" add full_name";
							Log.writeUserFile(log_name);
							Log.writeUserFile(sql);
							
							String full_name_id = Integer.toString(key);
							System.out.println("full_name_id : "+full_name_id);///////try////////	
							
							String sql_peo = "UPDATE `people` SET full_name_id="+full_name_id+" "
									+ " WHERE `index`='"+index_new+"'";
							connect.createStatement().executeUpdate(sql_peo);
									
							/* Log file */
							String log_people = strUser+" "+name+" "+surname+" edit people";
							Log.writeAdminFile(log_people);
							Log.writeUserFile(sql_peo);
									
							String file_path =  request.getParameter("file_upload");
					
							if(("null").equals(file_path))
							{
								
							}else{
								
								String src_path_full_name = request.getParameter("file_name_old");
								System.out.println("src_path_full_name:"+src_path_full_name);
								 String[] src_path_temp = src_path_full_name.split("\\\\");	
									int length = src_path_temp.length;
									
									
									String src_path_b = src_path_temp[length-1];
									
									String file_name_old = src_path_b;		
										
								System.out.println("file_upload:"+file_path);
								
								String sql_statement = "INSERT INTO `file`(`index`, `name_old`, `file_path`)"+
										   " VALUES ('"+index_new+"','"+file_name_old+"','"+file_path+"')";
								
								System.out.println("SQL_STATEMENT:"+sql_statement);
								
								connect.createStatement().executeUpdate(sql_statement);
								
								/* Log file */
								String log_file = strUser+" "+name+" "+surname+" add file";
								Log.writeAdminFile(log_file);
								Log.writeAdminFile(sql_statement);
								
							}
									
							
		
		%>
							<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ");	</script>
							<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_edit.jsp">
							
		<%
						} catch (SQLException e) {
							e.printStackTrace();
						}				
						
					}
					else {
						%>
						<script language="javascript"> alert("ข้อมูลไม่มีการเปลี่ยนแปลง กรุณาตรวจสอบอีกครั้งค่ะ");	</script>			
		<%
					}
						}
				

		
	}
	
	connect.close();
%>

<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
						
						<div id="main-content-ac">
						
							<br><br><br><br><br>
							
							<center>			
							<table width="1000" border="0">
								<form method="post" id="form" action="student_edit_name.jsp">
								
									<input type="hidden" name="checker" id="checker" value="ADD" />
									<input type="hidden" name="student_id" id="student_id" value="<%=tempId%>" />
									<input type="hidden" name="index" id="index" value="<%=people.getIndex() %>" />
									<input type="hidden" name="title_th" id="title_th" value="<%=people.getTitleTH() %>" />
									<input type="hidden" name="title_en" id="title_en" value="<%=people.getTitleEN() %>" />
									
						            <tr style="font-size:24px">
						                <td width="400" height="50">
						                	<label> <font size="5"><strong>ชื่อเดิม (ภาษาไทย)</strong></font> </label>
				         					<label><font size="5" color="#FF0000">*</font></label>
				         			</td>
						                <td width="400">
						                	<input type="hidden" name="name_th_old" id="name_th_old" value="<%=people.getNameTH() %>" />
						                	<input type="text" name="name_th_new" id="name_th_new" style="font-size: 20px;" value="<%=people.getNameTH() %>" readonly="readonly" required/>
						                </td>
						                <td>
						                	<center><img src="image/edit_icon.png" id="edit_name_th_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('name_th_new')" />
						                	</center>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td height="50">
						                	<font size="5"><strong>นามสกุลเดิม (ภาษาไทย)</strong></font>
				         					<label><font size="5" color="#FF0000">*</font></label>
				         				</td>
						                <td>
						                	<input type="hidden" name="surname_th_old" id="surname_th_old" value="<%=people.getSurnameTH() %>" />
											<input type="text" name="surname_th_new" id="surname_th_new" style="font-size: 20px;" value="<%=people.getSurnameTH() %>" readonly="readonly" required/>
						                </td>
						                <td>
						                	<center><img src="image/edit_icon.png" id="edit_surname_th_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('surname_th_new')" />
						                	</center>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td width="400" height="50">
						                	<label> <font size="5"><strong>ชื่อเดิม (ภาษาอังกฤษ)</strong></font> </label>
				         					<label><font size="5" color="#FF0000">*</font></label>
				         				</td>
						                <td width="400">
						                	<input type="hidden" name="name_en_old" id="name_en_old" value="<%=people.getNameEN() %>"/>	
						                	<input type="text" name="name_en_new" id="name_en_new" style="font-size: 20px;" value="<%=people.getNameEN() %>" readonly="readonly" required/>
						                </td>
						                <td>
						                	<center><img src="image/edit_icon.png" id="edit_name_en_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('name_en_new')" />
						                	</center>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td height="50"><font size="5">
						                	<strong>นามสกุลเดิม (ภาษาอังกฤษ)</strong></font>
				         					<label><font size="5" color="#FF0000">*</font></label>
				         				</td>
						                <td>
						                	<input type="hidden" name="surname_en_old" id="surname_en_old" value="<%=people.getSurnameEN() %>" />
											<input type="text" name="surname_en_new" id="surname_en_new" style="font-size: 20px;" value="<%=people.getSurnameEN() %>" readonly="readonly" required/>
						                </td>
						                <td>
						                	<center><img src="image/edit_icon.png" id="edit_surname_en_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('surname_en_new')" />
						                	</center>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td colspan="3">
						            		</br>
						            		<center>
													<div id="frm_add_file">
											
														<table style="font-size:15px; background-color: #f2f0f0;">
															<tr>
																<td>
																	<center>
																		   <input type="hidden" id="file_upload" name = "file_upload"/>
																		   <input type="hidden" id="file_name_old" name="file_name_old"/>
																		 
																		   
																		   		แนบไฟล์เอกสารที่เกี่ยวข้อง </br></br>
																				<input type="file" id="file" name="file"/><br />
																				<div id="upload" style="display: none;">Uploading..</div>
																				<div id="message">
																				</div>
																		  
												        		  			 
												        		  	</center>
												        		 </td>
												        		 
										        		  		 
															</tr>
																
														</table>
														</br>
													</div>
											</center>
						            	
						            	</td>
						            
						            </tr>
						            
						            
						            <tr style="font-size:24px">
						                <td height="50" colspan="3"><label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label></td>
						            </tr>
						    
						            <tr style="font-size:24px">
						                <td height="50">
						                	<center><input type="submit" name="save" id="save" value="save" class="buttonStyle" style=""/></center>
						                </td>
						        </form>
						                <td>
						                	<center><a href="student_edit.jsp"><button class="buttonStyle">cancel</button></a></center>
						              	</td>
						              	<td>
						             	</td>
						            </tr>
					      </table>
					      </center>
					      
					      <br><br><br>
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>



</body>
</html>